#include "daemon.hh"
#include <string>
#include "command_option.hh"
#include <iostream>
#include <fstream>

#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#else
#include <Windows.h>
#endif // WIN32

namespace kratos { namespace engine { namespace util {

bool daemonize(SignalFunc sig_quit, SignalFunc sig_term) {
#ifdef WIN32
    (void)sig_quit;(void)sig_term;
    // make PID file name
    std::string fileName = CommandOptionsRef.getPIDFilePath() + CommandOptionsRef.getServiceName() + ".pid";
    std::cout << "Generates PID file at " << fileName << std::endl;
    // write fo PID file
    std::ofstream file;
    file.open(fileName.c_str(), std::ios::out | std::ios::trunc);
    if (file) {
        file << std::to_string(::GetCurrentProcessId());
    }
    file.close();
    return true;
#else
    // make PID file name
    std::string fileName = CommandOptionsRef.getPIDFilePath() + CommandOptionsRef.getServiceName() + ".pid";
    std::cout << "Generates PID file at " << fileName << std::endl;
    if (daemon(1, 1) < 0) {
        return false;
    }
    signal(SIGQUIT, sig_quit);
    signal(SIGTERM, sig_term);
    // write fo PID file
    std::ofstream file;
    file.open(fileName.c_str(), std::ios::out | std::ios::trunc);
    if (file) {
        file << std::to_string(getpid());
    }
    file.close();
    return true;
#endif // WIN32
}

}}}
